#include <stdio.h>
#include <wchar.h>
#include "Private.h"
#include "Database.h"
#include "System.h"

/// <summary>
/// The DatabaseOpen function...
/// </summary>
int DatabaseOpen(const wchar_t *path, DatabasePtr pdb)
{
	if (pdb == NULL)
		return -1;

	/* Open the database file. */
	if ((pdb->handle = Open(path, 2 /* O_RDWR */, 0)) < 0)
		return -1;

	/* Lock the database for the current process. */
	if (FileLock(pdb->handle) < 0)
		return -2;

	int magic = 0x00000000;
	if (Read(pdb->handle, &magic, sizeof(magic)) < sizeof(magic))
		return -3;

	if (magic != 0x20406080)
		return -4;

	if (Read(pdb->handle, &pdb->item_count, sizeof(int)) < sizeof(int))
		return -3;

	pdb->item_index = 0;

	return 0;
}

/// <summary>
/// The DatabaseWrite function...
/// </summary>
int DatabaseWrite(DatabasePtr pdb, const void *data)
{
	if (pdb == NULL)
		return -1;

	if (data == NULL)
		return -1;

	return 0;
}

/// <summary>
/// The DatabaseRead function...
/// </summary>
int DatabaseReadFirst(DatabasePtr pdb, void *data)
{
	if (pdb == NULL)
		return -1;

	if (data == NULL)
		return -1;

	if (Seek(pdb->handle, DATA_ITEM_OFFSET, 0 /* SEEK_SET */) < 0)
		return -2;

	return 0;
}

/// <summary>
/// The DatabaseRead function...
/// </summary>
int DatabaseReadNext(DatabasePtr pdb, void *data)
{
	if (pdb == NULL)
		return -1;

	if (data == NULL)
		return -1;

	if (pdb->item_index <= 0)
		if (Seek(pdb->handle, DATA_ITEM_OFFSET, 0 /* SEEK_SET */) < 0)
			return -2;

	return 0;
}

/// <summary>
/// The DatabaseRead function...
/// </summary>
int DatabaseSetItemSize(DatabasePtr pdb, int size)
{
	if (pdb == NULL)
		return -1;

	if (size <= 0)
		return -2;

	pdb->item_size = size;

	return 0;
}

/// <summary>
/// The DatabaseClose function...
/// </summary>
int DatabaseClose(DatabasePtr pdb)
{
	if (pdb == NULL)
		return -1;

	if (FileUnlock(pdb->handle) < 0)
		/* return -2 */;

	if (Close(pdb->handle) < 0)
		return -1;

	return 0;
}

